package com.treeengine.game.audio;

import java.io.IOException;


import android.content.SyncResult;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;

public class Music implements IMusic, OnCompletionListener{

	MediaPlayer mediaPlayer;
	boolean isPrepared = false;
	
	public Music(AssetFileDescriptor assetDescriptor){
		mediaPlayer = new MediaPlayer();
		try {
			mediaPlayer.setDataSource(assetDescriptor.getFileDescriptor(),
					assetDescriptor.getStartOffset(),
					assetDescriptor.getLength());
			mediaPlayer.prepare();
			isPrepared = true;
			mediaPlayer.setOnCompletionListener(this);
		} catch (Exception e) {}
	}
	
	
	@Override
	public void onCompletion(MediaPlayer arg0) {
		synchronized (this) {
			isPrepared = false;
		}
	}

	@Override
	public void play() {
		if(mediaPlayer.isPlaying())
			return;
		try{
			synchronized (this) {
				if(!isPrepared)
					mediaPlayer.prepare();
				mediaPlayer.start();
			}	
		}catch(IllegalStateException e){
		}catch(IOException e){};
	}

	@Override
	public void stop() {
		mediaPlayer.stop();
		synchronized (this) {
			isPrepared = false;
		}
	}

	@Override
	public void pause() {
		if(mediaPlayer.isPlaying())
			mediaPlayer.pause();
		
	}

	@Override
	public void setLooping(boolean looping) {
		mediaPlayer.setLooping(looping);
		
	}

	@Override
	public void setVolume(float volume) {
		mediaPlayer.setVolume(volume, volume);
	}

	@Override
	public boolean isPlaying() {
		return mediaPlayer.isPlaying();
	}

	@Override
	public boolean isStopped() {
		return ! isPrepared;
	}

	@Override
	public boolean isLooping() {
		return mediaPlayer.isLooping();
	}

	/**
	 * 
	 * The dispose() method checks if the MediaPlayer is still 
	 * playing and, if so, stops it. Otherwise, the call to 
	 * MediaPlayer.release() will throw a RuntimeException.
	 * 
	 */
	@Override
	public void dispose() {
		if(mediaPlayer.isPlaying())
			mediaPlayer.stop();
		mediaPlayer.release();
	}

}
